/*
 * @Description:
 * @Author:
 * @Date: 2024-12-04 22:42:33
 * @LastEditTime: 2025-02-18 22:36:35
 * @LastEditors: XXX
 */
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import { useI18n } from 'vue-i18n'
import settings from '@/config/default/setting.config'
import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import { useStore } from './store'
import { UserActionTypes } from './store/modules/user/action-types'
import whiteList from './config/default/whitelist'
import { PermissionActionType } from './store/modules/permission/action-types'
import { ElMessage } from 'element-plus'
import i18n from '@/locales'

const getPageTitle = (key: string | undefined) => {
  const title = settings.title
  const hasKey = i18n.global.te(`route.${key}`)

  if (hasKey && typeof key === 'string') {
    const pageName = i18n.global.t(`route.${key}`)
    return `${pageName}-${title}`
  }

  return `${title}`
}

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  // to and from are both route objects. must call `next`.
  NProgress.start()

  const store = useStore()
  if (store.state.user.token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.state.user.roles.length === 0) {
        try {
          await store.dispatch(UserActionTypes.ACTION_GET_USER_INFO, undefined)
          const roles = store.state.user.roles
          store.dispatch(PermissionActionType.ACTION_SET_ROUTES, roles)
          const dynamicRoutes = store.state.permission.routes
          dynamicRoutes.forEach(route => router.addRoute(route))
          console.log('dynamicRoutes :>> ', dynamicRoutes);
          console.log('to :>> ', to);
          next({ ...to, replace: true })
        } catch (error) {
          store.dispatch(UserActionTypes.ACTION_RESET_TOKEN, undefined)
          ElMessage.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }

  }
})

router.afterEach((to: RouteLocationNormalized) => {
  console.log('afterEach')
  // to and from are both route objects.
  NProgress.done()

  // set page title
  document.title = getPageTitle(to.meta.title)
})
